package com.fedming.bottomnavigationdemo.Fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fedming.bottomnavigationdemo.Adapter.ConditionAdapter;
import com.fedming.bottomnavigationdemo.Adapter.DoctorAdvice;
import com.fedming.bottomnavigationdemo.Adapter.DoctorAdviceRecycleViewAdapter;
import com.fedming.bottomnavigationdemo.Fragment.BaseLazyFragment;
import com.fedming.bottomnavigationdemo.HomeActivity;
import com.fedming.bottomnavigationdemo.R;
import com.fedming.bottomnavigationdemo.Util.HttpUtils;
import com.google.api.Advice;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class HomeFragment extends BaseLazyFragment {
    private TextView name;
    private ImageView profile;
    private RecyclerView recyclerView;
    private TextView advice_home;
    private TextView gender;
    private TextView age;
    private TextView level;
    private TextView office;
    private TextView doctor_name;
    private TextView nurse_name;
    private TextView location_code;
    private TextView pno;
    private TextView admissionDate;

//    private List<DoctorAdvice> adviceList= new ArrayList<>();
//    private DoctorAdviceRecycleViewAdapter recycleviewadapter;

    OkHttpClient client;
    @Nullable
    @Override  //
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.home_fragment2,container,false);
        name = (TextView) view.findViewById(R.id.name);
        profile = (ImageView) view.findViewById(R.id.profile);
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_home);
        advice_home = (TextView) view.findViewById(R.id.advice_home);
        gender = (TextView) view.findViewById(R.id.gender);
        age = (TextView) view.findViewById(R.id.age);
        level = (TextView) view.findViewById(R.id.level);
        office = (TextView) view.findViewById(R.id.office);
        doctor_name = (TextView) view.findViewById(R.id.doctor_name);
        nurse_name = (TextView) view.findViewById(R.id.nurse_name);
        location_code = (TextView) view.findViewById(R.id.location_code);
        pno = (TextView) view.findViewById(R.id.admission_number);
        admissionDate = (TextView) view.findViewById(R.id.admission_time);
        mIsprepared = true;
        lazyLoad();
        Log.e("HomeFragment","onCreateView");
        return view;

    }

    public HomeFragment(){
         TAG = "HomeFragment";
    }

    @Override //懒加载，参考：https://blog.csdn.net/zhangrgg/article/details/81000238
    protected void lazyLoad() { //如果fragment已经初始化过一次，或者fragment是不可见的，或者fragment没有被初始化，都会直接返回
        if (!mIsprepared || !mIsVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        //UI和业务逻辑
        Log.e(TAG,"加载HomeFragment的UI");
        //getAsyn("http://10.181.255.203:8080//bed/index?id=1");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ChangeHome();
        //loadData();

    }

    private void ChangeHome() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap profile_bitmap = getIcon(HomeActivity.profile);
                getActivity().runOnUiThread(new Runnable() {//在主线程中更新Ui
                    @Override
                    public void run() {
                        profile.setImageBitmap(profile_bitmap);
                    }
                });
            }

        }).start();
        System.out.println("profile"+HomeActivity.profile);


        String gender_string = "男";
        name.setText(HomeActivity.name);
        if(HomeActivity.gender.equals("f"))
            gender_string = "女";
        gender.setText(gender_string);
        age.setText(HomeActivity.age+"岁");
        level.setText(HomeActivity.level+"级");
        office.setText(HomeActivity.office);
        doctor_name.setText(HomeActivity.doctor);
        nurse_name.setText(HomeActivity.nurse);
        location_code.setText(HomeActivity.room+"-"+HomeActivity.code);
        pno.setText(HomeActivity.pno);
        admissionDate.setText(HomeActivity.admissionDate);
        JSONArray conditions = HomeActivity.conditions;
        JSONArray advices = HomeActivity.advices;
        List<String> array = new ArrayList<String>();
        if(advices.size()>0){
            JSONObject obj = JSON.parseObject(advices.get(0).toString());
            advice_home.setText(obj.getString("content"));
        }

        for(Object object : conditions){
            array.add(object.toString());
        }
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        ConditionAdapter adapter1 = new ConditionAdapter(array);
        recyclerView.setAdapter(adapter1);
    }
    public static Bitmap getIcon(String path) {//根据路径获得图片的Bitmap
        Bitmap bitmap = null;
        try {
            java.net.URL url = new URL(path);//创建URL连接
            URLConnection connection = url.openConnection();//打开连接
            InputStream stream = connection.getInputStream();//获取输输入流
            bitmap = BitmapFactory.decodeStream(stream);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }

    //UI操作逻辑
    private void loadData(){
        name.setText("woqu");
        DoctorAdvice a1 = new DoctorAdvice("1月11日","医嘱， 就是医生根据病情和" +
                "治疗的需要对病人在饮食、用药、化验等方面的指示。医嘱是指医师在医疗活动中下达的医学指令" +
                "。医嘱内容及起始、停止时间应当由医师书写。医嘱内容应当准确、清楚，每项医嘱应当只包含一个" +
                "内容，并注明下达时间，应当具体到分钟。" +
                "",R.mipmap.news_icon,"最新医嘱");


    }
    private void GetInfo() {
        HttpUtils okObject = new HttpUtils();
        HomeActivity.t1 = "";
        HomeActivity.t2 = "";
        HomeActivity.t3 = "";
        new Thread(new Runnable() {
            @Override
            public void run() {
                String body = null;
                try {
                    String url = "http://"+HomeActivity.server_ip+":"+HomeActivity.info_port+"/bed/index?id="+HomeActivity.bedID;
                    System.out.println("url:"+url);
                    body = okObject.get(url).body().string();
                    Thread.sleep(2000);//等待get请求返回结果
                } catch (Exception e) {
                    //e.printStackTrace();
                    System.out.println("no response");
                }
                System.out.println("首页请求信息:"+body);
                if (body != null &&!JSON.parseObject(body).containsKey("timestamp")) {
                    JSONObject data = JSON.parseObject(body).getJSONObject("data");
                    HomeActivity.room = data.getString("room");
                    HomeActivity.code = data.getString("code");
                    HomeActivity.patientId = data.getInteger("patientId");
                    HomeActivity.name = data.getString("name");
                    HomeActivity.gender = data.getString("gender");
                    HomeActivity.profile = data.getString("profile");
                    HomeActivity.age = data.getInteger("age");
                    HomeActivity.admissionDate = data.getString("admissionDate");
                    HomeActivity.level = data.getInteger("level");
                    HomeActivity.pno = data.getString("pno");
                    HomeActivity.office = data.getString("office");
                    HomeActivity.doctor = data.getString("doctor");
                    HomeActivity.nurse = data.getString("nurse");
                    HomeActivity.conditions = data.getJSONArray("condition");
                    HomeActivity.advices = data.getJSONArray("advice");
                }
            }

        }).start();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.e("HomeFragment","onAttach");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("HomeFragment","onCreate");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.e("HomeFragment","onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e("HomeFragment","onStart");
        GetInfo();
        ChangeHome();
    }



    @Override
    public void onResume() {
        super.onResume();
        Log.e("HomeFragment","onResume");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e("HomeFragment","onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e("HomeFragment","onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHasLoadedOnce = false;
        mIsprepared = false;
        Log.e("HomeFragment","onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.e("HomeFragment","onDetach");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("HomeFragment","onPause");
    }

}
